package cn.easyplatform.studio.cmd.taskLink;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.utils.GlobalVariableService;
import cn.easyplatform.studio.vos.TypeLinkVo;

import java.util.List;


public class AddTaskLinkCmd implements Command<Boolean> {
    private String currentEntityId;
    private String childrenEntityId;
    private boolean isMainTask;
    public AddTaskLinkCmd(String currentEntityId, String childrenEntityId, boolean isMainTask)
    {
        this.currentEntityId = currentEntityId;
        this.childrenEntityId = childrenEntityId;
        this.isMainTask = isMainTask;
    }

    @Override
    public Boolean execute(CommandContext cc) {
        if (Strings.isBlank(currentEntityId))
            return false;
        //判断节点存在
        TypeLinkVo selectVo = cc.getTaskLink().getTaskLink("ep_"+cc.getProject().getId()+"_link",
                "ep_"+cc.getProject().getId()+"_task_link", currentEntityId);
        if (selectVo == null) {
            //添加节点
            String mainStr = isMainTask == true ? TypeLinkVo.ROOTENTITYID: TypeLinkVo.NODEENTITYID;
            TypeLinkVo addVo = new TypeLinkVo(currentEntityId, childrenEntityId, mainStr);
            boolean success = cc.getTaskLink().addTaskLink("ep_"+cc.getProject().getId()+"_task_link", addVo);
            if (success == false)
                return false;
            return addValidation(cc);
        }
        return true;
    }

    protected boolean addValidation(CommandContext cc) {
        TypeLinkVo updateVo = cc.getTaskLink().getTaskLink("ep_"+cc.getProject().getId()+"_link",
                "ep_"+cc.getProject().getId()+"_task_link", currentEntityId);
        if (updateVo == null)
            return false;
        synchronized (GlobalVariableService.getInstance().getDataTypeLinkVoList()) {
            List<TypeLinkVo> dataList = GlobalVariableService.getInstance().getDataTypeLinkVoList();
            dataList.add((TypeLinkVo)updateVo.clone());
        }
        return true;
    }
}
